<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="框架源码解析,">










<meta name="description" content="线程调度深入一个基本线程调度的例子:事件在IO线程产生,然后再UI线程被消费; 12345678910111213141516171819202122Observable.create(new Observable.OnSubscribe&amp;lt;String&amp;gt;() &amp;#123;    @Override    public void call(Subscriber&amp;lt;? super St">
<meta name="keywords" content="框架源码解析">
<meta property="og:type" content="article">
<meta property="og:title" content="RxJava源码详解-线程切换原理">
<meta property="og:url" content="https://zachaxy.github.io/2017/04/03/RxJava源码详解-线程切换原理/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="线程调度深入一个基本线程调度的例子:事件在IO线程产生,然后再UI线程被消费; 12345678910111213141516171819202122Observable.create(new Observable.OnSubscribe&amp;lt;String&amp;gt;() &amp;#123;    @Override    public void call(Subscriber&amp;lt;? super St">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://note.youdao.com/yws/public/resource/3a378f8ba029c8148bde85d73d9704c7/xmlnote/1853E77FF7BA42C5ABBAA8B9671EB41B/70">
<meta property="og:image" content="http://note.youdao.com/yws/public/resource/3a378f8ba029c8148bde85d73d9704c7/xmlnote/2AF59C14A4AC422F83E220C8C14059A8/68">
<meta property="og:updated_time" content="2019-09-01T11:13:24.297Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="RxJava源码详解-线程切换原理">
<meta name="twitter:description" content="线程调度深入一个基本线程调度的例子:事件在IO线程产生,然后再UI线程被消费; 12345678910111213141516171819202122Observable.create(new Observable.OnSubscribe&amp;lt;String&amp;gt;() &amp;#123;    @Override    public void call(Subscriber&amp;lt;? super St">
<meta name="twitter:image" content="http://note.youdao.com/yws/public/resource/3a378f8ba029c8148bde85d73d9704c7/xmlnote/1853E77FF7BA42C5ABBAA8B9671EB41B/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/04/03/RxJava源码详解-线程切换原理/">





  <title>RxJava源码详解-线程切换原理 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/04/03/RxJava源码详解-线程切换原理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">RxJava源码详解-线程切换原理</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-03T09:43:49+08:00">
                2017-04-03
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  4,181
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <h1 id="线程调度深入"><a href="#线程调度深入" class="headerlink" title="线程调度深入"></a>线程调度深入</h1><p>一个基本线程调度的例子:事件在IO线程产生,然后再UI线程被消费;</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">Observable.create(<span class="keyword">new</span> Observable.OnSubscribe&lt;String&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(Subscriber&lt;? <span class="keyword">super</span> String&gt; subscriber)</span> </span>&#123;</span><br><span class="line">        subscriber.onNext(<span class="string">"Hello RxJava!"</span>);</span><br><span class="line">        subscriber.onCompleted();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line">.subscribeOn(Schedulers.io())</span><br><span class="line">.observeOn(AndroidSchedulers.mainThread())</span><br><span class="line">.subscribe(<span class="keyword">new</span> Subscriber&lt;String&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCompleted</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"completed!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onError</span><span class="params">(Throwable e)</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">        System.out.println(s);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="subscribeOn-原理"><a href="#subscribeOn-原理" class="headerlink" title="subscribeOn()原理"></a>subscribeOn()原理</h2><p><code>subscribeOn()</code>用来指定<code>Observable</code>在哪个线程中执行事件流，也就是指定<code>Observable</code>中<code>OnSubscribe</code>(计划表)的<code>call()</code>方法在那个线程发射数据。下面通过源码分析<code>subscribeOn()</code>是怎样实现线程的切换的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Observable&lt;T&gt; <span class="title">subscribeOn</span><span class="params">(Scheduler scheduler)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//忽略这个 if 分支吧</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span> <span class="keyword">instanceof</span> ScalarSynchronousObservable) &#123;</span><br><span class="line">      <span class="keyword">return</span> ((ScalarSynchronousObservable&lt;T&gt;)<span class="keyword">this</span>).scalarScheduleOn(scheduler);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 重点看这个:this指的是调用线程切换方法subscribeOn()的Observerble ,</span></span><br><span class="line">    <span class="keyword">return</span> create(<span class="keyword">new</span> OperatorSubscribeOn&lt;T&gt;(<span class="keyword">this</span>, scheduler));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>subscribeOn()方法是 Observerble 中的方法,一旦调用了该方法,就会创建出一个新的 Observerble 对象;当然还是通过create(OnSubscribe)方法来创建Observerble ;</p>
<p>再来看一下新创建的这个Observerble 对象中的OnSubscribe的实现类内部是如何实现的;OperatorSubscribeOn是OnSubscribe的实现类,自然也要实现call方法来触发事件了.同时一旦换了新的Observerble ,那么最终的观察者订阅的自然也就是新的Observerble 了,这一点一定要明确;那么自然call方法中的参数也就持有了原始观察者的引用.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">OperatorSubscribeOn</span>&lt;<span class="title">T</span>&gt; <span class="keyword">implements</span> <span class="title">Observable</span>.<span class="title">OnSubscribe</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> Scheduler scheduler;   <span class="comment">//调度器</span></span><br><span class="line">    <span class="keyword">final</span> Observable&lt;T&gt; source;  <span class="comment">//原始Observable</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">//构造函数,传入原始的被观察者和线程调度器;</span></span><br><span class="line">  	<span class="function"><span class="keyword">public</span> <span class="title">OperatorSubscribeOn</span><span class="params">(Observable&lt;T&gt; source, Scheduler scheduler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.scheduler = scheduler;</span><br><span class="line">        <span class="keyword">this</span>.source = source;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//(1)原始观察者订阅了新的Observable后,将先执行此call方法(还记得订阅函数是如何实现的吗?)</span></span><br><span class="line">  <span class="comment">//这个参数的final的,其实是为了给内部类调用,内部类已经在其他线程了;</span></span><br><span class="line">  <span class="comment">//传入的参数是原始观察者;和上一篇操作符的原理类似,也是在call方法中创建了一个代理观察者,使其与原始被观察者订阅</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(<span class="keyword">final</span> Subscriber&lt;? <span class="keyword">super</span> T&gt; subscriber)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> Scheduler.Worker inner = scheduler.createWorker();  <span class="comment">//创建了一个worker对象,内部持有一个线程池</span></span><br><span class="line">        subscriber.add(inner);</span><br><span class="line"></span><br><span class="line"><span class="comment">//(2)call方法中使用传入的调度器创建的Worker对象的schedule方法切换线程,传入的Action0会作为一个参数传入runnable中</span></span><br><span class="line">        <span class="comment">//runnable的run方法中会调用action0的call方法,然后runnable又被添加到线程池中被执行;</span></span><br><span class="line">          inner.schedule(<span class="keyword">new</span> Action0() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                <span class="keyword">final</span> Thread thread = Thread.currentThread();</span><br><span class="line">          <span class="comment">//(3)根据外层call中传来的原始观察者,创建了一个新的观察者(代理观察者),而且代理观察者持有原始观察者的引用</span></span><br><span class="line">                    Subscriber&lt;T&gt; s = <span class="keyword">new</span> Subscriber&lt;T&gt;(subscriber) &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">                        <span class="comment">//(5) 新的(代理)观察者收到数据后直接发送给原始观察者</span></span><br><span class="line">                        subscriber.onNext(t);</span><br><span class="line">                    &#125;</span><br><span class="line">                    ...</span><br><span class="line">                &#125;;</span><br><span class="line">                <span class="comment">//(4)在切换的线程中，新的观察者订阅原始Observable，用来接收数据</span></span><br><span class="line">              <span class="comment">//代理观察者能收到数据的前提是因为代理观察者订阅了原始被观察者;</span></span><br><span class="line">              <span class="comment">//其实这个订阅的动作是在新线程中执行的.</span></span><br><span class="line">                source.unsafeSubscribe(s);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在<code>call</code>方法中通过<code>scheduler.createWorker().schedule(Action0)</code>完成线程的切换.</p>
<p>简单说:这里在subscribeOn()方法中新创建了一个Observable对象(代理Observable),于是发生了原始观察者与代理被观察者订阅的情况,于是代理被观察者中的call()方法被先执行,但是代理被观察者哪里有数据呢,还不是用老方法,又创建了一个代理观察者,然后让代理观察者与原始被观察者进行订阅,一旦发生订阅,数据就发出来了,数据发出来给了代理观察者,代理观察者的onNext()方法中有调用了原始观察者的onNext()方法;这不就解决了嘛,可是如何实现的线程切换呢?</p>
<p>提前说一下:这个Action0对象时作为参数传入一个Runnable实例中,然后将该runnable对象传入线程池,这样就实现了线程的切换,也就是说这个Action0()中的所有动作都是在新的线程池中执行的;</p>
<p>上述说说的一切动作都是在scheduler.createWorker().schedule(new Action0(XXX));都是在这个Action0()中发生的.</p>
<p>这里涉及到两个对象:<code>Scheduler</code>和<code>Worker</code>,究竟这是怎么实现的线程切换呢?</p>
<h3 id="Scheduler"><a href="#Scheduler" class="headerlink" title="Scheduler"></a>Scheduler</h3><p>其实在subscribeOn(Scheduler  scheduler)方法中传入的参数就是 Scheduler 对象;</p>
<p>由于RxJava中有多种调度器，我们就看一个简单的<code>Schedulers.newThread()</code>，其他调度器的思路是一样的.</p>
<p>先看一下<code>Schedulers</code>这个类,<code>Schedulers</code>就是一个调度器的管理器,大管家;</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Schedulers</span> </span>&#123;</span><br><span class="line">    <span class="comment">//各种调度器对象,看着眼熟吧.</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Scheduler computationScheduler;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Scheduler ioScheduler;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Scheduler newThreadScheduler;</span><br><span class="line">  </span><br><span class="line">    <span class="comment">//单例，Schedulers被加载的时候，上面的各种调度器对象已经初始化</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Schedulers INSTANCE = <span class="keyword">new</span> Schedulers();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//构造方法,在构造方法中初始化各种调度器</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Schedulers</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        RxJavaSchedulersHook hook = RxJavaPlugins.getInstance().getSchedulersHook();</span><br><span class="line">        ...</span><br><span class="line">          </span><br><span class="line">        <span class="comment">//这里只关注创建一个新的线程的调度器</span></span><br><span class="line">        Scheduler nt = hook.getNewThreadScheduler();</span><br><span class="line">        <span class="keyword">if</span> (nt != <span class="keyword">null</span>) &#123;</span><br><span class="line">            newThreadScheduler = nt;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//①.创建newThreadScheduler对象</span></span><br><span class="line">            newThreadScheduler = RxJavaSchedulersHook.createNewThreadScheduler();</span><br><span class="line">        &#125;</span><br><span class="line">      <span class="comment">//下面其余的线程不管.......................................</span></span><br><span class="line">    <span class="comment">//下面是Compute线程的创建  </span></span><br><span class="line">      Scheduler c = hook.getComputationScheduler();</span><br><span class="line">        <span class="keyword">if</span> (c != <span class="keyword">null</span>) &#123;</span><br><span class="line">            computationScheduler = c;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            computationScheduler = RxJavaSchedulersHook.createComputationScheduler();</span><br><span class="line">        &#125;</span><br><span class="line"><span class="comment">//下面是IO线程的创建;</span></span><br><span class="line">        Scheduler io = hook.getIOScheduler();</span><br><span class="line">        <span class="keyword">if</span> (io != <span class="keyword">null</span>) &#123;</span><br><span class="line">            ioScheduler = io;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            ioScheduler = RxJavaSchedulersHook.createIoScheduler();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">    <span class="comment">//②. 获取NewThreadScheduler对象,也就是我们在使用调度调用的该方法来获取一个新线程的调度器;</span></span><br><span class="line">  <span class="comment">//我们平时使用线程切换时,就是调用的 Schedulers.io(),Schedulers.newThread()等方法来获取一个Scheduler对象的!!</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Scheduler <span class="title">newThread</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> INSTANCE.newThreadScheduler;</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接着跟踪<code>RxJavaSchedulersHook.createNewScheduler()</code>，看看<code>newThreadScheduler</code>究竟是如何创建的?</p>
<p>我们发现无论是IO线程,Compute线程,还是NewThread线程调度器,都是<code>RxJavaSchedulersHook.createXXX()</code>方法创建出来了,其内部是用工厂方法实现的.</p>
<p>最终会找到一个叫<code>NewThreadScheduler</code>的类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">NewThreadScheduler</span> <span class="keyword">extends</span> <span class="title">Scheduler</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ThreadFactory threadFactory;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NewThreadScheduler</span><span class="params">(ThreadFactory threadFactory)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.threadFactory = threadFactory;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Worker <span class="title">createWorker</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> NewThreadWorker(threadFactory);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最终看到<code>NewThreadScheduler</code>就是我们调用<code>subscribeOn(Schedulers.newThread() )</code>传入的调度器对象，通过上面的分析,我们已经明白了<code>Scheduler</code> 的产生原理</p>
<p><strong>产生<code>Scheduler</code> 并不是最终目的,而是通过<code>Scheduler</code> 产生 <code>Worker</code>,然后调用<code>Worker.schedule(Action0)</code>实现线程的切换.</strong></p>
<h3 id="Worker"><a href="#Worker" class="headerlink" title="Worker"></a>Worker</h3><p>通过上面的分析,我们已经明白了<code>Scheduler</code> 的产生原理,产生<code>Scheduler</code> 并不是最终目的,而是通过<code>Scheduler</code> 产生 <code>Worker</code>,然后调用<code>Worker.schedule(Action0)</code>实现线程的切换.</p>
<p>每个调度器对象都有一个<code>createWorker</code>方法用于创建一个<code>Worker</code>对象，而<code>NewThreadScheduler</code>对应创建的<code>Worker</code>是一个叫<code>NewThreadWorker</code>的对象.</p>
<p>而在上面的分析中我们也看到了, <code>OperatorSubscribeOn</code>类中调用了</p>
<p><code>final Scheduler.Worker inner = scheduler.createWorker()</code>方法来得到一个 Worker,然后又调用 <code>inner.schedule(Action0)</code>实现线程的切换</p>
<p>接下来我们跟进<code>schedule()</code>方法查看其内部的实现原理.同样,这里的<code>Worker</code> 依然是以最简单的<code>NewThreadWorker</code> 为例.这里删减了部分代码,只留取对整体结构有用的部分.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NewThreadWorker</span> <span class="keyword">extends</span> <span class="title">Scheduler</span>.<span class="title">Worker</span> <span class="keyword">implements</span> <span class="title">Subscription</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ScheduledExecutorService executor;   <span class="comment">//线程池,在下面构造函数中进行初始化.</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NewThreadWorker</span><span class="params">(ThreadFactory threadFactory)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//创建一个线程池</span></span><br><span class="line">        ScheduledExecutorService exec = Executors.newScheduledThreadPool(<span class="number">1</span>, threadFactory);</span><br><span class="line">        executor = exec;</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="comment">//默认调用的是这个方法;</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Subscription <span class="title">schedule</span><span class="params">(<span class="keyword">final</span> Action0 action)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> schedule(action, <span class="number">0</span>, <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Subscription <span class="title">schedule</span><span class="params">(<span class="keyword">final</span> Action0 action, <span class="keyword">long</span> delayTime, TimeUnit unit)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> scheduleActual(action, delayTime, unit);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">  </span><br><span class="line">  <span class="comment">//重要：其实 worker.schedule()最终调用的是这个方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ScheduledAction <span class="title">scheduleActual</span><span class="params">(<span class="keyword">final</span> Action0 action, <span class="keyword">long</span> delayTime, TimeUnit unit)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//别紧张,源码中直接将传入的 action return回来了... 这一步相对于什么也没做;</span></span><br><span class="line">        Action0 decoratedAction = schedulersHook.onSchedule(action);</span><br><span class="line">        <span class="comment">//ScheduledAction就是一个Runnable对象，在run()方法中调用了Action0.call()</span></span><br><span class="line">        ScheduledAction run = <span class="keyword">new</span> ScheduledAction(decoratedAction);</span><br><span class="line">        Future&lt;?&gt; f;</span><br><span class="line">        <span class="keyword">if</span> (delayTime &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">            f = executor.submit(run);   <span class="comment">//将Runnable对象放入线程池中</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            f = executor.schedule(run, delayTime, unit);  <span class="comment">//延迟执行</span></span><br><span class="line">        &#125;</span><br><span class="line">        run.add(f);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> run;</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们发现<code>OperatorSubscribeOn</code>计划表中通过<code>NewThreadWorker.schedule(Action0)</code>，将<code>Action0</code>作为参数传入一个<code>Runnable</code>的实现类:<code>ScheduledAction</code>,然后将这个runnable放入到一个线程池中执行，这样就实现了线程的切换。</p>
<p>简单说:最原始的<code>subscribeOn()</code>—调用了—-<code>create(new OperatorSubscribeOn&lt;T&gt;(this, scheduler))</code>—-创建一个代理被观察者—-&gt;<code>OperatorSubscribeOn()</code>中实现了<code>call()</code>方法—-&gt;call()方法中调用了<code>NewThreadWorker.schedule(Action0)</code>—-<code>Action0</code>被包装称一个<code>RUnnable</code>对象,然后<code>schedule()</code>方法内部使用了线程池,创建一个新的线程,并将包装的<code>Runnable</code>对象传递进去,这样就实现了线程的切换</p>
<p>步骤:</p>
<ol>
<li>原始被观察者调用subscribeOn()方法准备切换线程,(这时候还没切换呢.)产生一个代理被观察者</li>
<li>原始订阅者订阅代理被观察者(明面代码上你能看得到的)</li>
<li>代理被观察者的<code>onSubscribe.call()</code>方法执行,提供了一个<code>Runnable</code>对象,也就是线程已经被切换了</li>
<li><strong>新线程</strong>中产生一个新的代理观察者,代理观察者订阅原始被观察者(接下来的动作也都是在新线程中执行)</li>
<li>原始被观察者发射数据,这个动作已经是在新线程中执行了</li>
<li>代理观察者收到数据,再将数据转发给原始观察者</li>
</ol>
<p>看这张图,帮助理解<br><img src="http://note.youdao.com/yws/public/resource/3a378f8ba029c8148bde85d73d9704c7/xmlnote/1853E77FF7BA42C5ABBAA8B9671EB41B/70" alt="image"></p>
<blockquote>
<p>此处用到了多线程的知识,多线程这一块还需要总结整理;</p>
</blockquote>
<h3 id="多次subscribeOn-的情况"><a href="#多次subscribeOn-的情况" class="headerlink" title="多次subscribeOn()的情况"></a>多次subscribeOn()的情况</h3><p>我们发现，每次使用<code>subscribeOn</code>都会产生一个新的<code>Observable</code>，并产生一个新的计划表<code>OnSubscribe</code>，目标Subscriber最后订阅的将是最后一次<code>subscribeOn</code>产生的新的<code>Observable</code>。在每个新的<code>OnSubscribe</code>的<code>call</code>方法中都会有一个产生一个新的线程，在这个新线程中订阅上一级<code>Observable</code>，并创建一个新的<code>Subscriber</code>接受数据，最终原始<code>Observable</code>将在第一个新线程中发射数据，然后传送给给下一个新的观察者，直到传送到目标观察者，所以多次调用<code>subscribeOn</code>只有第一个起作用（这只是表面现象，其实每个<code>subscribeOn</code>都切换了线程，只是最终目标<code>Observable</code>是在第一个<code>subscribeOn</code>产生的线程中发射数据的）</p>
<p>也就是说多次调用<code>subscribeOn()</code>方法其实不是只有第一次方法其作用,而是每次都起作用,这里说的第一次起作用其实说的是最原始的数据发射是在第一次subscribeOn()指定的线程,只不过我们很少关注中间数据的处理过程而已;</p>
<p>一张图理解多订阅的过程:</p>
<p><img src="http://note.youdao.com/yws/public/resource/3a378f8ba029c8148bde85d73d9704c7/xmlnote/2AF59C14A4AC422F83E220C8C14059A8/68" alt="image"></p>
<p>下面是多次线程切换的伪代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//第3个subscribeOn产生的新线程</span></span><br><span class="line"><span class="keyword">new</span> Thread()&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Subscriber s1 = <span class="keyword">new</span> Subscriber();</span><br><span class="line">        <span class="comment">//第2个subscribeOn产生的新线程</span></span><br><span class="line">        <span class="keyword">new</span> Thread()&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                Subscriber s2 = <span class="keyword">new</span> Subscriber();</span><br><span class="line">                <span class="comment">//第1个subscribeOn产生的新线程</span></span><br><span class="line">                <span class="keyword">new</span> Thread()&#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                        Subscriber&lt;T&gt; s3 = <span class="keyword">new</span> Subscriber&lt;T&gt;(subscriber) &#123;</span><br><span class="line">                            <span class="meta">@Override</span></span><br><span class="line">                            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(T t)</span> </span>&#123;</span><br><span class="line">                                subscriber.onNext(t);</span><br><span class="line">                            &#125;</span><br><span class="line">                            ...</span><br><span class="line">                        &#125;;</span><br><span class="line">                        <span class="comment">//①. 最后一个新观察者订阅原始Observable</span></span><br><span class="line">                        Observable.subscribe(s3);</span><br><span class="line">                        <span class="comment">//②. 原始Observable将在此线程中发射数据</span></span><br><span class="line"></span><br><span class="line">                              <span class="comment">//③. 最后一个新的观察者s3接受数据</span></span><br><span class="line"></span><br><span class="line">                              <span class="comment">//④. s3收到数据后，直接发送给s2，s2收到数据后传给s1,...最后目标观察者收到数据</span></span><br><span class="line">                         &#125; </span><br><span class="line">                &#125;.start();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;.start();</span><br></pre></td></tr></table></figure>

<h1 id="observeOn原理"><a href="#observeOn原理" class="headerlink" title="observeOn原理"></a>observeOn原理</h1><blockquote>
<p>还是需要进一步的整理</p>
</blockquote>
<p>observeOn调用的是lift操作符。lift操作符创建了一个代理的Observable，用于接收原始Observable发射的数据，然后在Operator中对数据做一些处理后传递给目标Subscriber。observeOn一样创建了一个代理的Observable，并创建一个代理观察者接受上一级Observable的数据，代理观察者收到数据之后会开启一个线程，在新的线程中，调用下一级观察者的onNext、onCompete、onError方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Observable&lt;T&gt; <span class="title">observeOn</span><span class="params">(Scheduler scheduler)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> observeOn(scheduler, RxRingBuffer.SIZE);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Observable&lt;T&gt; <span class="title">observeOn</span><span class="params">(Scheduler scheduler, <span class="keyword">int</span> bufferSize)</span> </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> observeOn(scheduler, <span class="keyword">false</span>, bufferSize);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Observable&lt;T&gt; <span class="title">observeOn</span><span class="params">(Scheduler scheduler, <span class="keyword">boolean</span> delayError, <span class="keyword">int</span> bufferSize)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span> <span class="keyword">instanceof</span> ScalarSynchronousObservable) &#123;</span><br><span class="line">      <span class="keyword">return</span> ((ScalarSynchronousObservable&lt;T&gt;)<span class="keyword">this</span>).scalarScheduleOn(scheduler);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> lift(<span class="keyword">new</span> OperatorObserveOn&lt;T&gt;(scheduler, delayError, bufferSize));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到使用observeOn(Scheduler scheduler)方法时,也是传入了一个scheduler,这和subscribeOn()方法如出一辙,,随着不断深入的调用,其最终使用 lift()操作符创建了一个Observable 对象.这里先不管lift,接着上面的lift()中创建了一个OperatorObserveOn类,其源码如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">OperatorObserveOn</span>&lt;<span class="title">T</span>&gt; <span class="keyword">implements</span> <span class="title">Observable</span>.<span class="title">Operator</span>&lt;<span class="title">T</span>, <span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Scheduler scheduler;</span><br><span class="line">    <span class="comment">//创建代理观察者，用于接收上一级Observable发射的数据,而这个child就是原始观察者.</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Subscriber&lt;? <span class="keyword">super</span> T&gt; call(Subscriber&lt;? <span class="keyword">super</span> T&gt; child) &#123;</span><br><span class="line">        <span class="keyword">if</span> (scheduler <span class="keyword">instanceof</span> ImmediateScheduler) &#123;</span><br><span class="line">            <span class="keyword">return</span> child;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (scheduler <span class="keyword">instanceof</span> TrampolineScheduler) &#123;</span><br><span class="line">            <span class="keyword">return</span> child;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            ObserveOnSubscriber&lt;T&gt; parent = <span class="keyword">new</span> ObserveOnSubscriber&lt;T&gt;(scheduler, child, delayError, bufferSize);</span><br><span class="line">            parent.init();</span><br><span class="line">            <span class="keyword">return</span> parent;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"> <span class="comment">//-----------------------------------我是分割线-------------------------------------------------------- </span></span><br><span class="line">  <span class="comment">/*</span></span><br><span class="line"><span class="comment">  先不管前面的复杂逻辑了,总之现在有了代理被观察者和代理观察者,像map那样发生了订阅,然后原始被观察者开始发数据了</span></span><br><span class="line"><span class="comment">  在代理观察者中,自然也有onNext,onCompleted(),onError()方法,但是在这三个方法后都调用了 schedule()函数</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">    <span class="comment">//代理观察者</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">ObserveOnSubscriber</span>&lt;<span class="title">T</span>&gt; <span class="keyword">extends</span> <span class="title">Subscriber</span>&lt;<span class="title">T</span>&gt; <span class="keyword">implements</span> <span class="title">Action0</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> Subscriber&lt;? <span class="keyword">super</span> T&gt; child;</span><br><span class="line">        <span class="keyword">final</span> Scheduler.Worker recursiveScheduler;</span><br><span class="line">        <span class="keyword">final</span> NotificationLite&lt;T&gt; on;</span><br><span class="line">        <span class="keyword">final</span> Queue&lt;Object&gt; queue;</span><br><span class="line">        <span class="comment">//接受上一级Observable发射的数据</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(<span class="keyword">final</span> T t)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (isUnsubscribed() || finished) &#123;</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (!queue.offer(on.next(t))) &#123;</span><br><span class="line">                onError(<span class="keyword">new</span> MissingBackpressureException());</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">   <span class="comment">//在代理观察者中,自然也有onNext,onCompleted(),onError()方法,但是在这三个方法后都调用了 schedule()函数</span></span><br><span class="line">            schedule();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCompleted</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            ...</span><br><span class="line">            schedule();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onError</span><span class="params">(<span class="keyword">final</span> Throwable e)</span> </span>&#123;</span><br><span class="line">            ...</span><br><span class="line">            schedule();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//开启新线程处理数据,切换线程就是在这里,重要的方法.</span></span><br><span class="line">        <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">schedule</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (counter.getAndIncrement() == <span class="number">0</span>) &#123;</span><br><span class="line">                recursiveScheduler.schedule(<span class="keyword">this</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      </span><br><span class="line">      </span><br><span class="line">        <span class="comment">// only execute this from schedule()</span></span><br><span class="line">        <span class="comment">//在新线程中将数据发送给目标观察者,注意这里是观察者,其call方法是因为实现了Action0接口,什么时候调用呢?</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">long</span> missed = <span class="number">1L</span>;</span><br><span class="line">            <span class="keyword">long</span> currentEmission = emitted;</span><br><span class="line">            <span class="keyword">final</span> Queue&lt;Object&gt; q = <span class="keyword">this</span>.queue;</span><br><span class="line">            <span class="keyword">final</span> Subscriber&lt;? <span class="keyword">super</span> T&gt; localChild = <span class="keyword">this</span>.child;</span><br><span class="line">            <span class="keyword">final</span> NotificationLite&lt;T&gt; localOn = <span class="keyword">this</span>.on;</span><br><span class="line">            <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">                <span class="keyword">while</span> (requestAmount != currentEmission) &#123;</span><br><span class="line">                    ...</span><br><span class="line">                    localChild.onNext(localOn.getValue(v));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>还记得<code>subscribeOn()</code>时传入的<code>Scheduler</code>吗,这个<code>observeOn()</code>也传入了一个<code>Scheduler</code>,和之前一样,通过这个<code>scheduler产生一个Worker</code>,然后调用<code>Worker.schedule(Action0)</code>实现线程的切换.与<code>subscribeOn()</code>不同的是,这个线程切换时在代理观察者执行<code>onNext()</code>中执行的,也就是说先把线程切换过去,然后代理观察者在执行的 <code>actual.onNext()</code>方法.</p>
<p>我们可以参照多次subscribeOn()的图解示例,可以把第二次subscribeOn()替换成observeOn(),那么在产生的第二个代理观察者给原始观察者发消息时,本来是在其onNext()方法中直接调用原始观察者的onNext()的,但是由于有observeOn(),所以在执行onNext的时候进行了线程切换,然后在调用原始观察者的onNext()</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>只要涉及到操作符，其实就是生成了一套代理的<code>Subscriber</code>(观察者)、<code>Observable</code>(被观察者)和<code>OnSubscribe</code>(计划表)。<code>Observable</code>最典型的特征就是链式调用，我们暂且将每一步操作称为一级。代理的<code>OnSubscribe</code>中的<code>call</code>方法就是让代理<code>Subscriber</code>订阅上一级<code>Observable</code>，直到订阅到原始<code>Observable</code>发射数据，代理<code>Subscriber</code>收到数据后，可能对数据做一些操作也有可能切换线程，然后将数据传送给下一级<code>Subscriber</code>，直到目标观察者接收到数据，目标观察者在那个线程接受数据取决于上一个<code>Subscriber</code>在哪一个线程调用目标观察者的方法。</p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/04/03/RxJava源码详解-线程切换原理/" title="RxJava源码详解-线程切换原理">https://zachaxy.github.io/2017/04/03/RxJava源码详解-线程切换原理/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/框架源码解析/" rel="tag"># 框架源码解析</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/04/03/RxJava源码详解-操作符原理/" rel="next" title="RxJava源码详解-操作符原理">
                <i class="fa fa-chevron-left"></i> RxJava源码详解-操作符原理
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/04/10/深度优先算法/" rel="prev" title="深度优先算法">
                深度优先算法 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#线程调度深入"><span class="nav-number">1.</span> <span class="nav-text">线程调度深入</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#subscribeOn-原理"><span class="nav-number">1.1.</span> <span class="nav-text">subscribeOn()原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Scheduler"><span class="nav-number">1.1.1.</span> <span class="nav-text">Scheduler</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Worker"><span class="nav-number">1.1.2.</span> <span class="nav-text">Worker</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多次subscribeOn-的情况"><span class="nav-number">1.1.3.</span> <span class="nav-text">多次subscribeOn()的情况</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#observeOn原理"><span class="nav-number">2.</span> <span class="nav-text">observeOn原理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
